<template>
  <div class="main" style="display: flex;font-family: Zpix,sans-serif;">
    <el-container>
      <el-aside :width="asideWidth" style="transition: width 0.3s; background-color: #333744;">
        <div class="navigation-title">导航</div>
        <el-menu
            :collapse="isCollapsed"
            active-text-color="#409EFF"
            background-color="#333744"
            class="el-menu-vertical-demo"
            default-active="2"
            router
            text-color="#ffffff"
        >
          <el-menu-item index="home">
            <template #title>
              <el-icon>
                <Location/>
              </el-icon>
              <span>首页</span>
            </template>
          </el-menu-item>
          <el-sub-menu index="add">
            <template #title>
              <el-icon>
                <Edit/>
              </el-icon>
              <span>添砖加瓦</span>
            </template>
            <el-menu-item index="newCanteenShop">
              食堂店铺
            </el-menu-item>
            <el-menu-item index="newPlaygroundContent">
              运动场
            </el-menu-item>
            <el-menu-item index="newTeachingBuildingContent">
              教学楼
            </el-menu-item>
            <el-menu-item index="newMaimaiChunithmContent">
              舞萌/中二
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item index="about">
            <template #title>
              <el-icon>
                <Help/>
              </el-icon>
              <span>关于</span>
            </template>
          </el-menu-item>
          <el-menu-item index="onlineChat">
            <template #title>
              <el-icon>
                <Message/>
              </el-icon>
              <span>在线聊天</span>
            </template>
          </el-menu-item>
          <el-menu-item index="chatWithAI">
            <template #title>
              <el-icon>
                <ChatDotRound/>
              </el-icon>
              <span>AI聊天(测试)</span>
            </template>
          </el-menu-item>
          <el-menu-item index="recentEdit">
            <template #title>
              <el-icon>
                <QuestionFilled/>
              </el-icon>
              <span>最近更改</span>
            </template>
          </el-menu-item>
          <el-menu-item index="currentUser" @click="handleUserClick">
            <template #title>
              <el-icon>
                <UserFilled/>
              </el-icon>
              <span>{{ currentUser }}</span>
            </template>
          </el-menu-item>
          <el-menu-item v-if="isLogging === false" index="register">
            <template #title>
              <el-icon>
                <AddLocation/>
              </el-icon>
              <span>注册</span>
            </template>
          </el-menu-item>
          <el-menu-item index="advice">
            <template #title>
              <el-icon>
                <Message/>
              </el-icon>
              <span>意见反馈</span>
            </template>
          </el-menu-item>
          <el-menu-item index="announcement">
            <template #title>
              <el-icon>
                <List/>
              </el-icon>
              <span>公告</span>
            </template>
          </el-menu-item>
          <el-menu-item v-if="isLogging === true" @click="logout">
            <template #title>
              <el-icon>
                <Close/>
              </el-icon>
              <span>退出登录</span>
            </template>
          </el-menu-item>

        </el-menu>
      </el-aside>
      <el-container>
        <!-- 外层包裹div实现固定 -->
        <div class="header-wrapper">
          <el-header
              style="display: flex; flex-direction: column; align-items: flex-start; height: 70px; padding: 10px;">
            <div style="display: flex; align-items: center;">
              <el-button style="width: 100px; margin-right: 10px;font-family: Zpix;"
                         @click="toggleAside">
                {{ isCollapsed ? '展开' : '收起' }}
              </el-button>
              <h2 style="font-size: 100%; font-family: Zpix, Helvetica, sans-serif; margin: 0;">
                <span style="font-size: 32px;">TJUT信息交流平台</span> 当前时间{{ currentTime }}
              </h2>
              <div>
                白天模式
                <el-switch v-model="isDark" inline-prompt
                           active-color="var(--el-fill-color-dark)"
                           inactive-color="var(--el-color-primary)"
                           @change="toggleDark"/>
                黑夜模式
              </div>
            </div>

          </el-header>
        </div>
        <el-main>
          <!-- 添加 transition 包裹 router-view -->
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component"/>
            </transition>
          </router-view>
        </el-main>
        <!-- 添加 el-footer -->
        <el-footer style="background-color: #333744; color: white; text-align: center; line-height: 60px;">
          <a href="https://space.bilibili.com/442305158?spm_id_from=333.33.0.0" target="_blank">
            <span style="color: yellow">@Tn9Gsaikou</span> </a> 2025
        </el-footer>
      </el-container>
    </el-container>
  </div>
  <!-- 登录对话框 -->
  <el-dialog v-model="loginDialogVisible" center class="custom-login-dialog" draggable title="用户登录" width="40%">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="80px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" placeholder="请输入密码" type="password"></el-input>
      </el-form-item>
    </el-form>
    <div class="verify-center" style="display:flex; justify-content: center">
      <slide-verify
          :h="280"
          :imgs="imgs"
          :l="42"
          :r="10"
          :w="520"
          slider-text="向右滑动"
          @fail="onFail"
          @refresh="onRefresh"
          @success="onSuccess"
      ></slide-verify>
    </div>
    <div style="text-align: center">{{ message }}</div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="loginDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitLogin">登录</el-button>
        <el-button type="success" @click="goToRegister">注册</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import axios from "axios";
import {ElForm, ElFormItem, ElInput, ElButton, ElMessage, ElMessageBox} from 'element-plus';
import router from "@/router/index.ts";
import {inject} from "vue";
import SlideVerify from 'vue3-slide-verify';
import {useDark, useToggle} from "@vueuse/core";

export default {
  data() {
    return {
      code: "",
      msg: "",
      loading: true,
      currentTime: "",
      currentUser: "",
      isLogging: false,
      isCollapsed: false,
      asideWidth: '180px',
      inshow: true,
      loginDialogVisible: false,
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      message: "",
      imgs: [
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
        "src/assets/sports.jpg"
      ]
    };
  },

  //生命周期函数，创建页面时调用
  mounted() {
    this.currentUser =
        localStorage.getItem('username') === null || localStorage.getItem('username') === ''
            ? '请登录' : localStorage.getItem('username');
    this.isLogging = localStorage.getItem('username') !== null;
    // 打印设备信息
    //this.test();
    // 每秒更新时间
    this.updateTime();
    setInterval(() => {
      this.updateTime();
    }, 1000);
    this.showInfo();
  },

  methods: {
    showInfo: function () {
      if (localStorage.getItem('isShow') === 'true') {
        ElMessageBox.confirm('2025/5/3重要更新：新增AI小助手(DeepSeek-V3)，欢迎来测！', {
          customClass: 'my-message-box',
          cancelButtonText: '取消',
          confirmButtonText: '继续',
          type: 'warning',
          title: '新增更新'
        }).then(() => {
          localStorage.setItem('isShow', 'false');
        });
      }
    },
    // 打印设备信息
    test: function () {
      axios.get("/user/test").then(res => {
        console.log(res.data);
      }).catch(err => {
        console.log(err);
      });
    },
    // 每秒更新时间
    updateTime: function () {
      const now = new Date();
      // 格式化日期和时间
      this.currentTime = now.toLocaleString();
    },

    // 退出登录
    logout: function () {
      if (localStorage.getItem("id") === null) {
        ElMessage.error("您还未登录");
        return;
      }
      ElMessageBox.confirm('是否确认退出登录？', {
        customClass: 'my-message-box',
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        type: 'warning',
        title: '正在尝试退出登录'
      }).then(() => {
        // 用户点击确认后的逻辑
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        localStorage.removeItem('id');
        this.$router.push('/home');
        ElMessage.success("退出登录成功");
        this.currentUser = "请登录";
        this.isLogging = false;
      }).catch(() => {
        // 用户点击取消后的逻辑
        ElMessage.info("您取消了退出登录");
      });
    },

    toggleAside: function () {
      this.isCollapsed = !this.isCollapsed;
      this.asideWidth = this.isCollapsed ? '0px' : '180px';
    },
    handleUserClick: function () {
      if (this.currentUser === '请登录') {
        this.loginDialogVisible = true;
      }
    },
    submitLogin: function () {
      const loginForm = this.loginForm;
      // 验证表单数据是否全部填写
      if (!loginForm.username || !loginForm.password) {
        ElMessage.warning('用户名和密码都不能为空哦');
        return; // 阻止表单提交
      }

      if (this.message !== '验证通过！') {
        ElMessage.warning('请完成滑动验证');
        return; // 阻止表单提交
      }

      console.log('提交表单数据：', loginForm);
      const postData = {
        username: loginForm.username,
        password: loginForm.password
      };

      axios.post('/user/login', postData)
          .then(response => {
            console.log('Success:', response.data.data);
            const userLoginVO = response.data.data;
            ElMessage.success("登录成功");
            // 存储token，这里假设存储到localStorage
            localStorage.setItem('token', userLoginVO.token);
            localStorage.setItem('username', userLoginVO.username);
            localStorage.setItem('id', userLoginVO.id);
            localStorage.setItem('isShow', 'true');
            console.log('token:', localStorage.getItem('token'));
            // 登录成功后跳转到主页
            router.push('/user/home');
            this.isLogging = true;
            this.loginDialogVisible = false;
            this.currentUser = localStorage.getItem('username') || "请登录";
          })
          .catch(error => {
            console.error('Error:', error);
            ElMessage.error("用户名或密码错误哦");
          });
    },
    onSuccess: function () {
      this.message = '验证通过！';
    },
    onFail: function () {
      this.message = '还原失败，请重试';
    },
    onRefresh: function () {
      this.message = '';
    },
    goToRegister: function () {
      this.loginDialogVisible = false;
      this.$router.push('/register');
    }
  }
};
</script>

<script setup>
import {
  AddLocation,
  ChatDotRound,
  Close,
  Edit,
  Help,
  List,
  Location,
  Message,
  QuestionFilled,
  UserFilled
} from "@element-plus/icons-vue";

import {useDark, useToggle} from "@vueuse/core";

const isDark = useDark();
const toggleDark = () => {
  const body = document.body;
  if (isDark.value) {
    body.setAttribute("data-theme", "dark");
  } else {
    body.removeAttribute("data-theme");
  }
  useToggle(isDark);
};
</script>

<style scoped>
.header-wrapper {
  position: sticky;
  top: 0;
  z-index: 1000;
  background-color: #333744;
  display: flex;
}

.main {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.navigation-title {
  font-size: 1rem;
  text-align: center;
  color: white;
  padding: 15px 0;
  margin: 0;
}

.el-container {
  display: flex;
  flex: 1;
}

.el-header {
  background-color: #333744 !important;
  color: white !important;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 60px;
}

.el-footer {
  background-color: #333744 !important;
  color: white !important;
  text-align: center;
  line-height: 60px;
  height: 60px;
  flex-shrink: 0;
}

.el-aside {
  background-color: #333744 !important;
  color: white !important;
  text-align: center;
  line-height: 200px;
}

.el-main {
  background-color: #e9eef3;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 160px;
  flex: 1;
}

.el-menu {
  background-color: #333744 !important;
  color: white !important;
}

.el-menu-item,
.el-sub-menu__title {
  display: flex !important;
  justify-content: center !important;
  padding: 0 10px !important;
}

.el-menu-item .el-icon,
.el-sub-menu__title .el-icon {
  margin-right: 0 !important;
  margin-left: 0 !important;
}

.el-menu-item span,
.el-sub-menu__title span {
  margin-left: 8px;
}

.el-menu-item {
  color: white !important;
}

.el-sub-menu__title {
  color: white !important;
}

.el-menu-item:hover {
  background-color: #444 !important;
}

.el-sub-menu__title:hover {
  background-color: #444 !important;
}

.el-button {
  color: black !important;
}

/* 定义淡入淡出动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.custom-login-dialog {
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-login-dialog .el-dialog__header {
  font-weight: bold;
  font-family: "Zpix", sans-serif;
}

.custom-login-dialog .el-dialog__body {
  padding: 20px 30px;
}

.custom-login-form {
  width: 100%;
}

.custom-login-input {
  width: 100%;
}

/* 黑夜模式下的样式 */
/* 黑夜模式下的样式 */
[data-theme="dark"] {
  background-color: #181818;
  color: white;
}

[data-theme="dark"] .el-main {
  background-color: #000000;
  color: #ffffff;
}

[data-theme="dark"] .el-main .bordered {
  border-color: #ffffff;
}

[data-theme="dark"] .el-main .text-bottom {
  text-shadow: 0 1px 0 #000000;
}

[data-theme="dark"] .el-button {
  background-color: #555; /* 按钮背景变为深灰色 */
  color: white !important; /* 按钮字体变为白色 */
}

[data-theme="dark"] .el-button:hover {
  background-color: #777; /* 按钮悬停背景变为稍浅的深灰色 */
  color: white; /* 按钮悬停时字体颜色保持白色 */
}

[data-theme="dark"] .el-menu {
  background-color: #333744;
  color: white;
}

[data-theme="dark"] .el-menu-item,
[data-theme="dark"] .el-sub-menu__title {
  color: white;
}

[data-theme="dark"] .el-menu-item:hover,
[data-theme="dark"] .el-sub-menu__title:hover {
  background-color: #444;
  color: white; /* 菜单项悬停时字体颜色保持白色 */
}
</style>